import 'package:flutter/material.dart';
import "package:get/get.dart";

import '../../common.dart';

final info = {}.obs;
final list = [].obs;
 final dynamicList = [].obs;



class UserHome extends StatefulWidget {
  const UserHome({super.key});

  @override
  State<UserHome> createState() => _SettingPageState();
}
class _SettingPageState extends State<UserHome> {

  final controller = TextEditingController(text: '');
final FocusNode _focusNode = FocusNode();

  final RxInt _index = 0.obs;

   initDate(){
   getData(url: '/bbs/userInfo').then((res) {
        info.value = res;
        list.value = res['wiki'];
        controller.text=res['profile'];

          if(res['identity']['type'].isEmpty){
            _index.value = 1;

             getData(url: '/bbs/my_article').then((res){
                    dynamicList.value = res;
              });
          }

        
      });
    }

    @override
    void initState() {
      super.initState();
      _focusNode.addListener(_handleFocusChange);
      WidgetsBinding.instance.addPostFrameCallback((_) {
        initDate();
        });
    }

    void _handleFocusChange() {
    setState(() {
      // 失去焦点时执行的操作
      if (!_focusNode.hasFocus) {
          debugPrint('用户输入内容: ${controller.text}');
          if(controller.text.isNotEmpty){
             postData(url: '/user/profile',data: {
              'profile':controller.text,
             }).then((res) {
                showTost('简介设置成功');
            });
          }
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    controller.dispose();
     _focusNode.dispose();
  }
    
    final isLoading = false.obs;
    final page = 1.obs;

 loadMore() {
    if (isLoading.value) return;

    isLoading.value = true;
    // 模拟异步加载
     getData(url: '/bbs/my_article',data: {'page':'${++page.value}'}).then((res){
      if(res.length>0){
        isLoading.value = false;
        for(var item in res){
         dynamicList.add(item);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {




    return Scaffold(
        body:
        NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          // 判断是否滚动到底部（距离底部还有 100 像素时触发）
          if (notification.metrics.pixels >= 
              notification.metrics.maxScrollExtent - 50) {
            loadMore();
            // 执行分页加载逻辑
          }
          return true;
        },
  child: 
         ListView(
          padding: EdgeInsets.only(top: 0),
            children: [
              Stack(
                children: [
                  Image.asset(
                    'static/zhuye.png',
                    height: 150,
                    fit: BoxFit.fill,
                  ),
                  Positioned(
                    left: 8.0,
                    top: 20,
                    child: IconButton(
                      onPressed: () {
                        Get.back();
                        print('object');
                      },
                      icon: Image.asset(
                        'static/images/back.png',
                        width: 22,
                        fit: BoxFit.fitWidth,
                      ),
                    ),
                  ),
                  Positioned(
                    top: 100,
                    left: 0,
                    right: 0,
                    child: Container(
                      height: 60,
                      decoration: BoxDecoration(
                          color: Color(0xffffffff),
                          borderRadius: BorderRadius.circular(10)),
                    ),
                  ),
                  Positioned(
                      top: 80,
                      left: 15,
                      child: Obx(() => Row(
                            children: [
                              Container(
                                height: 70,
                                width: 70,
                                decoration: BoxDecoration(
                                    color: Color(0xffffffff),
                                    border: Border.all(
                                        color: Color(0xffffffff), width: 2),
                                    borderRadius: BorderRadius.circular(70)),
                                child: ClipOval(
                                  child: Image.network("${info['headimg']}",
                                      width: 60, height: 60, fit: BoxFit.fill,
                                      errorBuilder: (context, error, stackTrace) {
                                    return SizedBox(
                                      width: 60,
                                    );
                                  }),
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(top: 20, left: 10),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      '${info['name']}',
                                      style: TextStyle(fontSize: 18),
                                    ),
                                    Text(
                                      'UID:${info['uuid']}',
                                      style: TextStyle(
                                          fontSize: 12, color: Color(0xff999999)),
                                    ),
                                  ],
                                ),
                              )
                            ],
                          ))),
                ],
              ),
              Container(
                  
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  child: TextField(
                    focusNode: _focusNode,
                    controller: controller,
                    maxLines:null,
                    keyboardType:TextInputType.multiline,
                    style: TextStyle(fontSize: 12),
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.symmetric(vertical: 20),
                      hintStyle: TextStyle(color: Color(0xff999999)),
                      border: InputBorder.none, // 隐藏输入框默认边框
                      hintText: '点击这里，填写简介', // 提示文本
                    ),
                  )),


              Obx(()=>

              Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
                 info.isNotEmpty && info['identity']['type'] ==1 || info.isNotEmpty && info['identity']['type']==2?
               Container(
                margin: EdgeInsets.only(left: 15,right: 15,bottom: 15),
                decoration: BoxDecoration(
                    color: Color(0xffE4F1FE),
                    borderRadius: BorderRadius.circular(20)),
                padding:
                    EdgeInsets.only(left: 15, right: 15, top: 5, bottom: 5),
                child: 
                  Row(
                    children: [
                      Image.asset( info['identity']['type'] ==2?'static/images/zuzhi.png':'static/images/xingqu.png', width: 15),
                      SizedBox(width: 5),
                      Text(
                        '${info['identity']['title']}',
                        style: TextStyle(fontSize: 14.5),
                      )
                    ],
                  )
              ):SizedBox()
            ],
              )
             
              ),


              Padding(
                padding: EdgeInsets.symmetric(horizontal: 15),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Obx(
                      () => Row(
                        children: [
                          Column(
                            children: [
                              Text(
                                '获赞',
                                style:
                                    TextStyle(fontSize: 12, color: Color(0xff999999)),
                              ),
                              Text(
                                '${info['up_count']}',
                                style: TextStyle(
                                    fontSize: 16, fontWeight: FontWeight.bold),
                              ),
                            ],
                          ),
                          SizedBox(
                            width: 30,
                          ),
                          Column(
                            children: [
                              Text(
                                '关注',
                                style:
                                    TextStyle(fontSize: 12, color: Color(0xff999999)),
                              ),
                              Text(
                                '${info['follow_count']}',
                                style: TextStyle(
                                    fontSize: 16, fontWeight: FontWeight.bold),
                              ),
                            ],
                          ),
                          SizedBox(
                            width: 30,
                          ),
                          Column(
                            children: [
                              Text(
                                '粉丝',
                                style:
                                    TextStyle(fontSize: 12, color: Color(0xff999999)),
                              ),
                              Text(
                                '${info['fans_count']}',
                                style: TextStyle(
                                    fontSize: 16, fontWeight: FontWeight.bold),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Container(
                        width: 72,
                        height: 28,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: Color(0xfff5f5f5),
                            borderRadius: BorderRadius.circular(28)),
                        child: GestureDetector(
                              onTap: () async {
                                if(info.isNotEmpty &&info['identity']['type']!=''||info.isNotEmpty &&info['identity']['type'].length > 0){
                                    final shouldRefresh =
                                  await toNamed('/user/personal/edit_info') ?? false;
                              if (shouldRefresh) {

                                getData(url: '/bbs/userInfo').then((res) {
                                 
                                list.value = res['wiki'];
                                });
                              }
                                }else{
                                  showTost('请先申请通过OSG认证');
                                }
                              
                            },
                          child: Text(
                            '编辑百科',
                            style: TextStyle(fontSize: 12),
                          ),
                        ))
                  ],
                ),
              ),
              Container(
                height: 10,
                margin: EdgeInsets.symmetric(vertical: 15),
                color: Color(0xfff5f5f5),
              ),
              Padding(
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Obx(() => Row(
                            children: [
                                
                              
                              if(info.isNotEmpty &&info['identity']['type']!=''||info.isNotEmpty &&info['identity']['type'].length > 0)
                              Container(
                                  decoration: BoxDecoration(
                                      border: Border(
                                          bottom: BorderSide(
                                              width: 2,
                                              color: _index.value == 0
                                                  ? Color(0xff6A3BD9)
                                                  : Color(0xffffffff)))),
                                  child: GestureDetector(
                                    onTap: () => {
                                      _index.value = 0,
                                      },
                                    child: Text(
                                      '公海百科',
                                      style: TextStyle(
                                          color: _index.value == 0
                                              ? Color(0xff6A3BD9)
                                              : Color(0xff333333),
                                          fontSize: 16),
                                    ),
                                  )),
                              if(info.isNotEmpty &&info['identity']['type']!=''||info.isNotEmpty &&info['identity']['type'].length > 0)
                              SizedBox(
                                width: 20,
                              ),

                              Container(
                                  decoration: BoxDecoration(
                                      border: Border(
                                          bottom: BorderSide(
                                              width: 2,
                                              color: _index.value == 1
                                                  ? Color(0xff6A3BD9)
                                                  : Color(0xffffffff)))),
                                  child: GestureDetector(
                                    onTap: () => {
                                        _index.value = 1,
                                        dynamicList.value=[],
                                        getData(url: '/bbs/my_article').then((res){
                                          dynamicList.value = res;
                                        })
                                      },
                                    child: Text(
                                      '动态',
                                      style: TextStyle(
                                          color: _index.value == 1
                                              ? Color(0xff6A3BD9)
                                              : Color(0xff333333),
                                          fontSize: 16),
                                    ),
                                  )),
                            ],
                          )),
                      Row(
                        children: [
                          Image.asset(
                            'static/zhanting.png',
                            width: 15,
                            fit: BoxFit.fitWidth,
                          ),
                          SizedBox(
                            width: 2,
                          ),
                          GestureDetector(
                            onTap: (){
                               toNamed('/web_webview?url=https://test.cg-online.cn/ZGYH/index.html');
                            },
                            child: Text(
                            '我的展厅',
                            style: TextStyle(fontSize: 12),
                          ),
                          )
                          ,
                        ],
                      ),
                    ],
                  )),
              SizedBox(
                height: 15,
              ),
              Obx(() => _index.value == 0
                  ? Padding(
                      padding: EdgeInsets.symmetric(horizontal: 15),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: list
                            .map((item) => Column(
                        crossAxisAlignment: CrossAxisAlignment.start,

                                  children: [
                                    Text(
                                      '${item['title']}',
                                      style: TextStyle(fontSize: 16,fontWeight:FontWeight.bold),
                                    ),
                                    SizedBox(height: 3,),
                                    Text(
                                      '${item['text']}',
                                      style: TextStyle(
                                        fontSize: 12,
                                      ),
                                    ),
                                    SizedBox(
                                      height: 20,
                                    ),
                                  ],
                                ))
                            .toList(),
                      ))
                  : NotificationLayout())
            ],
          )
    ));
  }
}

class NotificationLayout extends StatelessWidget {
  const NotificationLayout({super.key});

  @override
  Widget build(BuildContext context) {



    final width = MediaQuery.of(context).size.width / 3.4;
    return 
    Obx(()=>
    
    
    Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Row(
            // children: [
            //   // 你的子元素
            //   GestureDetector(
            //     onTap: () => {toNamed('/users/user/all_collection')},
            //     child: Container(
            //       padding: EdgeInsets.symmetric(vertical: 2, horizontal: 5),
            //       margin: EdgeInsets.only(left: 15, bottom: 15),
            //       decoration: BoxDecoration(
            //           border: Border.all(color: Color(0XFFDDDDDD)),
            //           borderRadius: BorderRadius.circular(5)),
            //       child: Row(
            //         children: [
            //           Image.asset(
            //             'static/images/heji.png',
            //             width: 16,
            //             fit: BoxFit.fitWidth,
            //           ),
            //           Text(
            //             '合集名称合集',
            //             style: TextStyle(fontSize: 12),
            //           )
            //         ],
            //       ),
            //     ),
            //   )
            // ],
          ),
        ),


      
      
      if(dynamicList.isEmpty)
      isdata(),

      for (var item in dynamicList.asMap().entries)

        Container(
          margin: EdgeInsets.only(left: 15, right: 15,bottom: 30),
          child:
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Row(
              children: [
                CircleAvatar( 
                    radius: 17,
                    backgroundImage:NetworkImage('${item.value['headimg']}'),
                    child:  SizedBox(
                                width: 34,
                              ),
                  ),
                SizedBox(width: 8),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '${item.value['name']}',
                      style:
                          TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                    ),
                    SizedBox(height: 4),
                    Text(
                      '${item.value['time']}',
                      style: TextStyle(fontSize: 12, color: Colors.grey),
                    ),
                  ],
                ),
              ],
            ),
            SizedBox(height: 10),
            Text(
              '${item.value['text']}',
              style: TextStyle(fontSize: 14, color: Color(0xff333333)),
            ),
            SizedBox(height: 10),
            Wrap(
              spacing: 5,
              runSpacing: 5,
              children: 
               [

             for (var items in item.value['images'])
              ClipRRect(
                  borderRadius: BorderRadius.circular(5),
                  child: Image.network(
                    items,
                    width: width,
                    height: width,
                    fit: BoxFit.fill,
                  ))
             ],
            ),
            SizedBox(
              height: 15,
            ),
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
              Row(
                children: [
 GestureDetector(
                onTap: () => {
                  Get.dialog(
                    AlertDialog(
                        backgroundColor: Color(0xffffffff),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10)),
                        content: Container(
                          height: 140,
                          child: Column(
                            children: [
                              SizedBox(
                                height: 25,
                              ),
                              Text(
                                '您的动态将被永久删除，无法找回，',
                                style: TextStyle(fontSize: 12),
                              ),
                              SizedBox(
                                height: 5,
                              ),
                              Text(
                                '确认删除?',
                                style: TextStyle(fontSize: 12),
                              ),
                              SizedBox(
                                height: 30,
                              ),
                              Row(
                                children: [
                                  Expanded(
                                    child:
                                    GestureDetector(
                                      onTap: (){
                                        postData(url: '/bbs/delArticle',data:  {
                                          "id":'${item.value['id']}',
                                          'topic_id':'${item.value['topic_id']}',
                                        }).then((res){
                                          if(res!=null){
                                            Get.back();
                                             showTost('删除成功');
                                            //  list.value[item.key].
                                            print('item.key');
                                            print(item.key);
                                             dynamicList.removeAt(item.key);
                                             dynamicList.refresh();
                                          }
                                        });
                                      },
                                      child: Container(
                                    width: 80,
                                    height: 35,
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                        color: Color(0XFFF5F5F5),
                                        borderRadius:
                                            BorderRadius.circular(35)),
                                    child: Text(
                                      '确认删除',
                                      style: TextStyle(
                                          fontSize: 12,
                                          color: Color(0XFFEF0000)),
                                    ),
                                  ),
                                    )
                                  ,
                                  ),
                                  SizedBox(
                                    width: 15,
                                  ),
                                  Expanded(
                                    child:
                                    GestureDetector(
                                      onTap: (){
                                        Get.back();
                                      },
                                      child: Container(
                                      width: 80,
                                      height: 35,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        color: Color(0XFFF5F5F5),
                                        borderRadius: BorderRadius.circular(35),
                                        gradient: LinearGradient(
                                          colors: [
                                            Color(0xff2189E7),
                                            Color(0xffBF67F8),
                                          ],
                                          begin: Alignment.topLeft, // 渐变开始的位置
                                          end: Alignment.bottomRight, // 渐变结束的位置
                                        ),
                                      ),
                                      child: Text(
                                        '取消',
                                        style: TextStyle(
                                            fontSize: 12,
                                            color: Color(0XFFFFFFFF)),
                                      ),
                                    ),
                                    )
                                     ,
                                  )
                                ],
                              )
                            ],
                          ),
                        )),
                  )
                },
                child: Text('删除'),
              ),
              SizedBox(width: 15,),
              Text(item.value['status']==0?'(审核中)':item.value['status']==2?'(未通过)':'',style: TextStyle(fontSize: 12,color: Color.fromARGB(255, 40, 120, 255)),)
                ],
              )
             ,

              Container(
                child: Row(
                  children: [
                    Image.asset(
                      'static/images/aixin.png',
                      width: 15,
                    ),
                    Text('${item.value['up_count']}',style: TextStyle(fontSize: 12),),
                    SizedBox(width: 30),
                    Image.asset(
                      'static/images/liekai.png',
                      width: 15,
                    ),
                    Text('${item.value['down_count']}',style: TextStyle(fontSize: 12),),
                    SizedBox(width: 30),

                    GestureDetector(
                      onTap: (){
                        toNamed('/talk/deatil?article_id=${item.value['id']}&is_up=false&is_down=false&down_count=${item.value['down_count']}&up_count=${item.value['up_count']}');
                      },
                      child:  Image.asset(
                      'static/images/chat.png',
                      width: 15,
                    )
                      ,
                    )
                   ,
                    Text('${item.value['comment_count']}',style: TextStyle(fontSize: 12),),

                  ],
                ),
              )
            ]),
          ]),
        ),

        
      ],
    )
    );
 
  }
}
